package com.example.administrator.szb.activity.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.bumptech.glide.Glide;
import com.bumptech.glide.util.Util;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.WecomeActivity;
import com.example.administrator.szb.bean.JClientBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtils;
import com.example.administrator.szb.util.AutoSoftUtils;
import com.example.administrator.szb.util.FinishActivity;
import com.example.administrator.szb.util.IosDiaolog;
import com.example.administrator.szb.util.JPushUtils;
import com.example.administrator.szb.util.LogoutDialog;
import com.example.administrator.szb.util.Permission;
import com.example.administrator.szb.util.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by stone on 2017/12/29.
 */

public abstract class MVPBaseFragmentActivity<V,T extends BasePresenter> extends FragmentActivity  implements View.OnTouchListener,Permission.IRoot,View.OnLayoutChangeListener{
    protected T mPresenter;//presenter对象
    protected Context context;
    protected FragmentManager fm = getSupportFragmentManager();
    protected IosDiaolog iosDiaolog;
    protected Activity activity;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = this;
        context = this;
        iosDiaolog = new IosDiaolog(this);
        FinishActivity.add(this);
        EventBus.getDefault().register(this);
        //JPushInterface.setAlias(this, 0, SampleApplicationLike.getUserloginInstance().getId() + "");
        JPushUtils.setALias(this,null);

        setScreen();
    }
    //重启App
    public void restartApp() {
        FinishActivity.finish();
        Intent intent = new Intent(this, WecomeActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        this.startActivity(intent);
        android.os.Process.killProcess(android.os.Process.myPid());  //结束进程之前可以把你程序的注销或者退出代码放在这段代码之前
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
    }
    protected void setScreen(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    private EditText tmpEdit;
    private int tmpEditId;
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        //触摸的是EditText并且当前EditText可以滚动则将事件交给EditText处理；否则将事件交由其父类处理
        if ((view.getId() ==tmpEditId && canVerticalScroll(tmpEdit))) {
            view.getParent().requestDisallowInterceptTouchEvent(true);
            if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                view.getParent().requestDisallowInterceptTouchEvent(false);
            }
        }
        return false;
    }
    public void setEditEvent(EditText mtmpEdit,int mtmpEditId){
        tmpEditId=mtmpEditId;
        tmpEdit=mtmpEdit;
        tmpEdit.setOnTouchListener(this);
    }
    /**
     * EditText竖直方向是否可以滚动
     * @param editText  需要判断的EditText
     * @return  true：可以滚动   false：不可以滚动
     */
    private boolean canVerticalScroll(EditText editText) {
        //滚动的距离
        int scrollY = editText.getScrollY();
        //控件内容的总高度
        int scrollRange = editText.getLayout().getHeight();
        //控件实际显示的高度
        int scrollExtent = editText.getHeight() - editText.getCompoundPaddingTop() -editText.getCompoundPaddingBottom();
        //控件内容总高度与实际显示高度的差值
        int scrollDifference = scrollRange - scrollExtent;

        if(scrollDifference == 0) {
            return false;
        }

        return (scrollY > 0) || (scrollY < scrollDifference - 1);
    }

    /**
     * 关闭当前界面
     * @param view
     */
    public void onFinish(View view){
        finish();
    }
    public FragmentTransaction getFragmentTransaction(){

        FragmentTransaction transaction = fm.beginTransaction();

        return transaction;
    }
    /**
     * 设置标题栏颜色
     */
    protected void setBarColor(){
        StatusBarUtil.setColor(this, R.color.basecolor,0);
    }
    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        if (SampleApplicationLike.FLAGS == -1) {//flag为-1说明程序被杀掉
            restartApp();
        }else {
            setBarColor();
            initView();
            fm = getSupportFragmentManager();
            mPresenter = createPresenter();//创建presenter
            if (mPresenter!=null){
                mPresenter.setActivity(this);
                mPresenter.attachView((V)this);//view与presenter建立关联
            }

            initEvent();
            initData();
        }

    }
    @Subscribe(threadMode = ThreadMode.MAIN,priority = 100) //在ui线程执行 优先级100
    public void onDataSynEvent(JClientBean event) {
        LogoutDialog.showDialog(context,event.getMsg());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(Util.isOnMainThread()&&!this.isFinishing())
        {
            try {
                Glide.with(this).pauseRequests();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        EventBus.getDefault().unregister(this);
        if (mPresenter!=null){
            mPresenter.detachView();
        }
        iosDiaolog.hide();
        HttpUtils.cancleTag(this);
    }

    protected abstract  T createPresenter();
    protected abstract void initView();
    protected abstract void initEvent();
    protected abstract void initData();
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(iosDiaolog!=null&&iosDiaolog.getPopupWindow().isShowing()&&!iosDiaolog.isAtuoHide()){
            return false;
        }
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (AutoSoftUtils.isShouldHideInput(v, ev)) {
                hideKey(v);
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
    public void hideKey(View v){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            editTextOut(false);
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
    public void editTextOut(boolean isshow){
/*if (isshow){
            QTLog.e("软键盘弹起");
        }else {
            QTLog.e("软键盘关闭");
        }*/
    }
    //Activity最外层的Layout视图
    private View activityRootView;
    //屏幕高度
    private int screenHeight = 0;
    //软件盘弹起后所占高度阀值
    private int keyHeight = 0;
    public void initKey(){
        activityRootView = findViewById(R.id.root_layout);
        //获取屏幕高度
        screenHeight = this.getWindowManager().getDefaultDisplay().getHeight();
        //阀值设置为屏幕高度的1/3
        keyHeight = screenHeight/3;
    }
    @Override
    protected void onResume() {
        super.onResume();
        if (activityRootView!=null){
            //添加layout大小发生改变监听器
            activityRootView.addOnLayoutChangeListener(this);
        }
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right,
                               int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {

        //old是改变前的左上右下坐标点值，没有old的是改变后的左上右下坐标点值

//      System.out.println(oldLeft + " " + oldTop +" " + oldRight + " " + oldBottom);
//      System.out.println(left + " " + top +" " + right + " " + bottom);


        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > keyHeight)) {
            editTextOut(true);
            //Toast.makeText(MainActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();

        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > keyHeight)) {
            editTextOut(false);
            //Toast.makeText(MainActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();

        }
    }
    /**
     * 权限申请结果
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            haveRoot(requestCode);
        } else {
            onRequestPermissionsFail(requestCode);
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    /**
     * 拥有权限就执行
     * @param requestCode
     */
    @Override
    public void haveRoot(int requestCode) {
        onRequestPermissionsSuccess(requestCode);
    }

    /**
     * 同上，
     * @param requestCode 请求码
     */
    protected  void onRequestPermissionsSuccess(int requestCode){

    }
    protected  void onRequestPermissionsFail(int requestCode){
        Permission.showMissingPermissionDialog(context);
    }


}
